class Menu {
  constructor(obj, links) {
    $(obj.firstElementChild).html(links.map(this.item.bind(this)))
  }

  item(v) {
    if (v.child)
      return `<li class="nav-item dropdown"><a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
${v.name}</a>
        <ul class="dropdown-menu">${v.child.map(this.ditem).join('')}</ul></li>`
    return `<li class="nav-item"><a class="nav-link" href="${
      v.link || v.url
    }" target="main">${v.name}</a></li>`
  }

  ditem(v) {
    return `<li class="dropdown-item"><a href="${
      v.link || v.url
    }" target="main">${v.name}</a></li>`
  }
}

class MyMenu {
  constructor(title, menu1, menu2) {
    if (menu2 === undefined) {
      let s = Math.ceil(menu1.length / 2.0)
      menu2 = menu1.slice(s)
      menu1 = menu1.slice(0, s)
    }
    let n = (this.navs = document.querySelector('.toph').children)
    this.left = new Menu(n[1], menu1)
    n[2].innerHTML = title
    this.right = new Menu(n[3], menu2)
    this.c = n[0]
    this.c1 = n[0].querySelector('span')
    this.t = setInterval(this.update_clock.bind(this), 1000)
    let links = (this.links = $('nav a,nav li'))
    this.links.click(ev => {
      if (ev.target.href) {
        console.log(ev.target)
        this.current = ev.target
        this.links.removeClass('active')
        $(ev.target).parents('li').toggleClass('active')
      }
    })
    this.u = n[4]
    this.show_user()
    window.onkeydown = function (ev) {
      if (ev.key === 'F5') this.current.click()
    }
    n[2].onclick = function () {
      this.current.click()
    }.bind(this)

    // 默认选中首页菜单项并加载首页内容
    this.setDefaultPage(menu1)
  }

  // 设置默认显示的页面（首页）
  setDefaultPage(menu1) {
    // 找到“首页”菜单项
    const homePage = menu1.find(item => item.name === '首页')
    if (homePage) {
      // 找到对应的链接并触发点击事件
      const homeLink = $(`a[href="${homePage.url}"]`)
      if (homeLink.length > 0) {
        // 模拟点击首页链接
        this.current = homeLink[0] // 设置当前选中的菜单项
        this.links.removeClass('active') // 移除所有菜单项的活动状态
        homeLink.parents('li').addClass('active') // 给首页菜单项添加活动状态

        // 触发模拟点击行为来加载“首页”页面内容
        this.loadPage(homePage.url)
      }
    }
  }

  // 加载页面内容
  loadPage(url) {
    const iframe = document.querySelector('iframe') // 假设页面内容是通过 iframe 加载的
    if (iframe) {
      iframe.src = url // 设置 iframe 的 src 为首页的 URL，加载首页内容
    }
  }

  async show_user() {
    let u = await fetch('/-/auth.userinfo').then(v => v.json())
    if (u.user) this.u.innerHTML = `Welcome ${u.user}`
    this.user = u
  }

  update_clock() {
    let t = new Date()
    this.c.title = t.toISOString().slice(0, 19) + ' UTC'
    this.c1.innerHTML =
      ' ' +
      new Date(t.getTime() - t.getTimezoneOffset())
        .toISOString()
        .slice(0, 19)
        .replace('T', ' ')
  }
}
